<template>
  <div class="app">
    <div class="title">
      <div class="icon" @click="hanldeBack">
        <el-icon><ArrowLeftBold /></el-icon>
      </div>
      <div class="title-left">覆膜报工单</div>
      <div class="title-right" @click="hanldeReportList">覆膜报工单</div>
    </div>
    <div style="margin-top: 20px">
      <el-form
        :model="form"
        :rules="rules"
        :disabled="flag"
        ref="userRef"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-form-item label="机台" prop="machineName">
            <el-input
              style="width: 100%"
              v-model="form.machineName"
              readonly
              placeholder="请选择机台"
            />
          </el-form-item>
        </el-row>
        <el-row :gutter="20">
          <el-form-item label="日报日期" prop="orderDate">
            <el-date-picker
              style="width: 100%"
              v-model="form.orderDate"
              type="date"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-row>

        <el-row :gutter="20">
          <el-form-item label="当班日期" prop="dutyDate">
            <el-date-picker
              style="width: 100%"
              v-model="form.dutyDate"
              type="date"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-row>
        <el-row :gutter="20">
          <el-form-item label="维修保养时长" prop="duration">
            <el-input
              v-model="form.duration"
              pattern="[0-9]*"
              style="width: 100%"
              placeholder="请输入维修保养时长"
            >
              <template #append>h</template>
            </el-input>
          </el-form-item>
        </el-row>
        <el-row :gutter="20">
          <el-form-item label="关联单据" prop="relatedOrder">
            <el-input
              v-model="form.relatedOrder"
              style="width: 100%"
              readonly
              placeholder="自动带出"
            ></el-input>
          </el-form-item>
        </el-row>
      </el-form>
    </div>

    <el-collapse v-model="activeNames">
      <el-collapse-item disabled title="人员明细" name="2">
        <template #title>
          <el-icon style="color: #4479f6">
            <Position />
          </el-icon>
          <span class="title">人员明细</span>
        </template>
        <el-button
          size="small"
          type="primary"
          style="margin-bottom: 10px"
          v-if="!route.query.info"
          @click="handleAddReportUserList"
        >
          选择人员
        </el-button>
        <div class="order-form">
          <el-form
            :model="data"
            ref="reportUserListForm"
            :disabled="flag"
            class="data-form"
          >
            <el-table
              :data="data.orderUserList"
              border
              :header-cell-class-name="mustPeople"
              :row-class-name="tableRowClassName"
              :summary-method="getSummaries"
              show-summary
            >
              <el-table-column
                label="序号"
                width="60"
                type="index"
                align="center"
              />
              <!-- <el-table-column
                              label="工位"
                              min-width="100"
                              prop=""
                              align="center"
                          ></el-table-column> -->
              <el-table-column
                label="员工工号"
                width="160"
                prop="userCode"
                align="center"
              ></el-table-column>
              <el-table-column
                  label="员工姓名"
                  width="160"
                  prop="userName"
                  align="center"
                ></el-table-column>
              <el-table-column
                label="计件工资(元)"
                min-width="150"
                prop="piecePrice"
                align="center"
              >
                <!-- <template #default="scope">
                                  <el-form-item
                                      :prop="'reportUserList.' + scope.$index + '.wagesPiece'"
                                      :rules="[
                                          {
                                              required: true,
                                              message: '计件工资',
                                              trigger: 'blur',
                                          },
                                      ]"
                                  >
                                      <el-input
                                          @blur="changeWagesSum(scope.row, scope.$index)"
                                          v-model="scope.row.wagesPiece"
                                          type="number"
                                          placeholder="请输入计件工资(元)"
                                      >
                                          <template #append>元</template>
                                      </el-input>
                                  </el-form-item>
                              </template> -->
              </el-table-column>
              <!-- <el-table-column
                              label="补助工资(元)"
                              min-width="160"
                              prop="wagesSubsidy"
                              align="center"
                          >
                              <template #default="scope">
                                  <el-form-item
                                    
                                  >
                                      <el-input
                                          @blur="changeWagesSum(scope.row, scope.$index)"
                                          v-model="scope.row.wagesSubsidy"
                                          type="number"
                                          placeholder="请输入补助工资(元)"
                                      >
                                          <template #append>元</template>
                                      </el-input>
                                  </el-form-item>
                              </template>
                          </el-table-column>
                          <el-table-column
                              label="合计工资(元)"
                              min-width="120"
                              prop="wagesSum"
                              align="center"
                          ></el-table-column> -->
              <el-table-column
                prop="proportion"
                label="岗位占比"
                align="center"
              >
                <template #default="scope">
                  <el-input
                    type="number"
                    pattern="[0-9]*"
                    @input="limitInput('proportion', scope.row)"
                    :disabled="flag"
                    v-model="scope.row.proportion"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                v-if="!flag"
                align="center"
                fixed="right"
                class-name="small-padding fixed-width"
              >
                <template #default="scope">
                  <el-button
                    link
                    type="primary"
                    icon="Delete"
                    @click="handleDelete(scope.row)"
                  ></el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </div>
      </el-collapse-item>
      <el-collapse-item disabled title="完成工作量明细" name="3">
        <template #title>
          <el-icon style="color: #4479f6">
            <Position />
          </el-icon>
          <span class="title">完成工作量明细</span>
        </template>
        <el-button
          size="small"
          type="primary"
          style="margin-bottom: 10px"
          v-if="!route.query.info"
          @click="handleAddPieceList"
        >
          选择生产单
        </el-button>
        <div class="order-form">
          <el-form
            :model="data"
            ref="orderWorkListForm"
            :disabled="flag"
            class="data-form"
          >
            <el-table
              :data="data.orderWorkList"
              ref="orderWorkListRef"
              border
              :header-cell-class-name="mustReport"
              :summary-method="getSummariesWorkList"
              show-summary
            >
              <el-table-column
                label="序号"
                width="60"
                type="index"
                align="center"
              />
              <!-- <el-table-column
                                    label="类型"
                                    align="center"
                                    width="80"
                                    
                                    prop="type"
                                >
                                    <template v-slot="{ row }">
                                        <el-tag
                                            :type="row.type == 1 ? 'success' : ''"
                                            effect="dark"
                                        >
                                            {{ row.type == 1 ? '封面' : '内文' }}
                                        </el-tag>
                                    </template>
                                </el-table-column> -->
              <el-table-column
                label="生产单编码"
                min-width="150"
                align="center"
                prop="produceNo"
              ></el-table-column>
              <!-- <el-table-column
                label="产品信息"
                min-width="150"
                align="center"
                
                prop="produceCode"
              ></el-table-column> -->
              <el-table-column
                label="下单日期"
                min-width="120"
                align="center"
                
                prop="submitDate"
              >
                <template v-slot="{ row }">
                  {{ row.submitDate ? row.submitDate.split("T")[0] : "" }}
                </template>
              </el-table-column>
              <el-table-column
                label="品种"
                min-width="150"
                align="center"
                
                prop="breedType"
              ></el-table-column>
              <el-table-column
                label="组成"
                min-width="150"
                align="center"
                
                prop="composition"
              ></el-table-column>
              <el-table-column
                label="规格型号"
                min-width="150"
                align="center"
                
                prop="specification"
              >
                <template #default="scope">
                  <dict-tag
                    :options="mes_paper_specs"
                    :value="scope.row.specification"
                  />
                </template>
              </el-table-column>
              <!-- <el-table-column
                label="覆膜尺寸"
                min-width="150"
                align="center"
                
                prop="coveringSize"
              ></el-table-column>
              <el-table-column
                label="成品尺寸"
                min-width="150"
                align="center"
                
                prop="finishedProduct_size"
              ></el-table-column> -->
              <el-table-column
                label="覆膜令数"
                min-width="150"
                align="center"
                prop="ream"
              ></el-table-column>
              <el-table-column
                label="覆膜张数"
                min-width="120"
                align="center"
                prop="coveringPageNum"
              >
              </el-table-column>
              <el-table-column
                label="完工数量"
                min-width="120"
                align="center"
                prop="completeCount"
              >
                <template #default="scope">
                  <!-- <el-form-item :prop="'orderUserList.' + scope.$index + '.piecePrice'"
                                            :rules="[{ required: true, message: '计件工资', trigger: 'blur' }]"> -->
                  <el-input
                    @blur="changeCompleteCount(scope.row, scope.$index)"
                    v-model="scope.row.completeCount"
                    type="number"
                    placeholder="请输入完成数量"
                  ></el-input>
                  <!-- </el-form-item> -->
                </template>
              </el-table-column>
              <el-table-column
                label="计件令数"
                min-width="120"
                align="center"
                prop="pieceReam"
              >
                <!-- <template #default="scope">
                                        <el-input
                                            @blur="changePieceLing(scope.row, scope.$index)"
                                            v-model="scope.row.pieceReam"
                                            type="number"
                                            placeholder="请输入计件令数"
                                        ></el-input>
                                    </template> -->
              </el-table-column>
              <el-table-column
                label="计件标准"
                min-width="120"
                align="center"
                prop="pieceStandard"
              >
                <template #default="scope">
                  <!-- <el-form-item :prop="'orderUserList.' + scope.$index + '.piecePrice'"
                                            :rules="[{ required: true, message: '计件工资', trigger: 'blur' }]"> -->
                  <el-input
                    @blur="changePieceLing(scope.row, scope.$index)"
                    v-model="scope.row.pieceStandard"
                    type="number"
                    placeholder="请输入计件标准"
                  ></el-input>
                  <!-- </el-form-item> -->
                </template>
              </el-table-column>
              <el-table-column
                label="计件金额"
                align="center"
                prop="piecePrice"
              ></el-table-column>
              <el-table-column
                label="备注"
                width="150"
                prop="remark"
                align="center"
              >
                <template #default="scope">
                  <el-input
                    v-model="scope.row.remark"
                    placeholder="请输入内容"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                v-if="!route.query.info"
                align="center"
                fixed="right"
                class-name="small-padding fixed-width"
              >
                <template #default="scope">
                  <el-button
                    link
                    type="primary"
                    icon="Delete"
                    @click="handleDeleteOrder(scope.row)"
                  ></el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </div>
      </el-collapse-item>
    </el-collapse>
    <userWorkListVue
      :visible="searchPeopleVisible"
      :userWorkList="userWorkList"
      @changeUpdate="changePeopleData"
      @cancel="
        () => {
          searchPeopleVisible = false;
        }
      "
    ></userWorkListVue>
    <pieceList
      :visible="pieceListOpen"
      :params="params"
      @changeUpdate="changePieceListData"
      :orderSelectList="orderSelectList"
      @cancel="
        () => {
          pieceListOpen = false;
        }
      "
    ></pieceList>
    <el-button class="footer" v-if="!flag" @click="submitForm">提交</el-button>
  </div>
</template>

<script setup>
import {
  addCover,
  getCoverById,
  listReportCare,
} from "@/api/production/coverReport.js";
import { getById } from '@/api/basicInfo/workbench'
import userWorkListVue from "../userWorkList.vue";
import useTagsViewStore from "@/store/modules/tagsView";
import useUserStore from "@/store/modules/user";
import pieceList from "./pieceList.vue";
import { toNumber } from "@/utils/ruoyi";
import { nextTick } from "vue";
import { ElMessage } from "element-plus";
const route = useRoute();
const router = useRouter();
const searchVisible = ref(false);
const searchPeopleVisible = ref(false);
const pieceListOpen = ref(false);
const tagsViewStore = useTagsViewStore();
const { proxy } = getCurrentInstance();
const userInfo = useUserStore();
const peopleSelectList = ref([]);
const orderSelectList = ref([]);
const activeNames = ["1", "2", "3", "4"];
const userRef = ref(null);
const orderUserListForm = ref(null);
const flag = ref(false);
const sumPriceSum = ref(0);
const totalAmount = ref(0);
const totalAmountH = ref(0);
const userWorkList = ref([]);
const params = ref({});
const data = reactive({
  reportCareList: [], // 保养
  orderUserList: [], // 人员
  orderWorkList: [], // 完成
  form: {
    type: "1",
  },
  rules: {
    machineName: [{ required: true, message: "机台不能为空", trigger: "blur" }],
    orderDate: [
      { required: true, message: "报工日期不能为空", trigger: "blur" },
    ],
  },
});
nextTick(() => {
  form.value.createBy = userInfo.name;
});
const {
  mes_paper_package,
  mes_paper_specs,
  ems_order_print_color,
  ems_produce_book_size,
  ems_order_binding_mode,
} = proxy.useDict(
  "mes_paper_package",
  "ems_order_print_color",
  "ems_produce_book_size",
  "ems_order_binding_mode",
  "mes_paper_specs"
);
const { form, rules, reportCareList, orderUserList, orderWorkList } =
  toRefs(data);
if (route.query?.uid) {
  getCoverById({ pid: route.query.uid }).then((res) => {
    Object.assign(form.value, { ...res.data });
    params.value = { machineId: res.data.machineId };
    // reportCareList.value = res.data.reportCareList
    orderUserList.value = res.data.orderUserList;
    orderWorkList.value = res.data.orderWorkList;
    if (route.query.info) {
      flag.value = true;
    }
  });
}
// 根据机台id 查询 机台
const getWorkBranch = () => {
  getById({ pid: route.query.id }).then((res) => {
    userWorkList.value = res.data.mesMachineUserList.map((item) => {
      return {
        ...item,
        name: item.mesUsers.name,
        code: item.mesUsers.code,
      };
    });
    form.value.machineName = res.data.machineName;
    form.value.machineId = res.data.pid;
    form.value.machineType = res.data.type;
    params.value = { machineId: form.value.machineId };
    form.value.headName = res.data.headUserName;
    listReportCare({ status: 2, machineNo: res.data.machineNo }).then((res) => {
      form.value.relatedOrder = res.data[0]?.code;
    });
  });
};
const hanldeBack = () => {
  router.push("todo");
};
const hanldeReportList = () => {
    router.push({
        path: '/reportList',
        query: {
            type: 4,
        },
    })
}
// 合计
const getSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    const values = data.map((item) => Number(item[column.property]));
    if (!values.every((value) => Number.isNaN(value))) {
      sums[index] = `${values.reduce((prev, curr) => {
        const value = Number(curr);
        if (!Number.isNaN(value)) {
          return toNumber(prev + curr, 2);
        } else {
          return toNumber(prev, 2);
        }
      }, 0)}`;
      if (column.property == "piecePrice") {
        sumPriceSum.value = toNumber(Number(sums[index]), 2);
      }
    } else {
      sums[index] = "";
    }
  });
  return sums;
};
// 合计
const getSummariesWorkList = (param) => {
  const { columns, data } = param;
  const sums = [];
  const fieldsToSum = ["piecePrice", "piecePriceH"];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    if (fieldsToSum.includes(column.property)) {
      const values = data.map((item) => Number(item[column.property]));
      if (!values.every((value) => Number.isNaN(value))) {
        sums[index] = `${values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!Number.isNaN(value)) {
            return toNumber(prev + curr, 2);
          } else {
            return toNumber(prev, 2);
          }
        }, 0)}`;
        if (column.property == "piecePrice") {
          totalAmount.value = toNumber(Number(sums[index]), 2);
        }
      } else {
        sums[index] = "";
      }
    } else {
      sums[index] = "";
    }
  });
  return sums;
};

function limitInput(key, row) {
  row[key] =
    ("" + row[key]) // 第一步：转成字符串
      .replace(/[^\d^\.]+/g, "")
      .replace(/^0+(\d)/, "$1")
      .replace(/^\./, "0.")
      .match(/^\d*(\.?\d{0,1})/g)[0] || "";
  handleTotalCount();
}
const handleTotalCount = () => {
  // 计算计件工资
  const totalLing = orderWorkList.value.reduce((prev, item) => {
    prev += Number(item.piecePrice || 0);
    return prev;
  }, 0);
  const totalProportion = orderUserList.value.reduce((prev, item) => {
    prev += Number(item.proportion || 0);
    return prev;
  }, 0);
  orderUserList.value.forEach((item) => {
    if (item.proportion) {
      item.piecePrice = toNumber(
        (Number(item.proportion) / totalProportion) * totalLing,
        2
      );
    }
  });
};
const mustPeople = (obj) => {
  let mustColumns = [3, 4];
  if (mustColumns.includes(obj.columnIndex)) {
    return "must";
  }
};
// 令数等于完工数量除1000
const changeCompleteCount = (row, index) => {
  orderWorkList.value[index].pieceReam = toNumber(
    Number(row.completeCount || 0) / 1000,
    2
  );
  changePieceLing(row, index);
};
// 获取当前时间
const getCurrentDateTime = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  const hours = String(now.getHours()).padStart(2, "0");
  const minutes = String(now.getMinutes()).padStart(2, "0");
  const seconds = String(now.getSeconds()).padStart(2, "0");
  form.value.orderDate = `${year}-${month}-${day} `;
};
getCurrentDateTime();
// 打开机台页面
const openDialog = () => {
  searchVisible.value = true;
};
// 选择人员
const handleAddReportUserList = () => {
  peopleSelectList.value = orderUserList.value;
  searchPeopleVisible.value = true;
};

// 选中的人员
const changePeopleData = (row) => {
  const codeSet = new Set(orderUserList.value.map((data) => data.id));
  row.forEach((item) => {
    if (!codeSet.has(item.id)) {
      orderUserList.value.push({
        ...item,
        remark: null,
        userCode: item.code,
        userName: item.name,
        piecePrice: null,
        subsidyPrice: null,
      });
      codeSet.add(item.id);
    }
  });
  orderUserList.value = orderUserList.value.filter((item) =>
    row.some((rowItem) => rowItem.id === item.id)
  );
  if (orderWorkList.value.length > 0) {
    handleTotalCount();
  }
  searchPeopleVisible.value = false;
};
// 合计工资
const changeWagesSum = (row, index) => {
  orderUserList.value[index].sumPrice =
    Number(row.piecePrice) + Number(row.subsidyPrice);
};
// 删除
const handleDelete = (row) => {
  proxy.$modal.confirm("是否确认删除该数据？").then(function () {
    orderUserList.value = orderUserList.value.filter(
      (item) => item.id !== row.id
    );
    handleTotalCount()
    proxy.$modal.msgSuccess("删除成功");
  });
};
const handleDeleteOrder = (row) => {
  proxy.$modal.confirm("是否确认删除该数据？").then(function () {
    orderWorkList.value = orderWorkList.value.filter((item) =>
      item.pid ? item.pid !== row.pid : item.coveringId != row.coveringId
    );
    handleTotalCount()
    proxy.$modal.msgSuccess("删除成功");
  });
};

// 选择生产单
const handleAddPieceList = () => {
  orderSelectList.value = orderWorkList.value;
  pieceListOpen.value = true;
};
// 选中的数据
const changePieceListData = (row) => {
  const codeSet = new Set(orderWorkList.value.map((data) => data.coveringId));
  row.forEach((item) => {
    if (!codeSet.has(item.coveringId)) {
      orderWorkList.value.push({
        ...item,
        fromType: "1", // 来源类型  1生产单， 2纸张
        bookCode: item.bookNo,
        orderName: item.bookName,
        labeling: item.pieceView,
      });
      codeSet.add(item.coveringId);
    }
  });
  pieceListOpen.value = false;
};
// 计算计件令数
const changePieceLing = (row, index) => {
  // if (
  //     Number(orderWorkList.value[index].completeCount) +
  //         Number(orderWorkList.value[index].totalNum) >
  //     Number(orderWorkList.value[index].maxNum)
  // ) {
  //     orderWorkList.value[index].completeCount = undefined
  //     return ElMessage({
  //         message: '完工数量+累计已上报数量不能大于最大允许上报数量',
  //         type: 'success',
  //     })
  // }
  // 完工数量/1000 * 印张
  orderWorkList.value[index].piecePrice = toNumber(
    (Number(orderWorkList.value[index].pieceReam) || 0) *
      (Number(row.pieceStandard) || 0),
    2
  );
  // changeAmount()
  handleTotalCount();
};
// //  计算计件金额
// const changeAmount = (row, index) => {
//     // 计件令数*计件标准
//     orderWorkList.value[index].piecePrice = toNumber(
//         (Number(row.pieceLing) || 0) * (Number(row.pieceStandard) || 0),
//         2
//     )
// }
// //  计算计件金额（换版）
// const changeAmountH = (row, index) => {
//     // 换版数量*计件标准（换版）
//     orderWorkList.value[index].piecePriceH = toNumber(
//         (Number(row.exchangeNum) || 0) * (Number(row.pieceStandardH) || 0),
//         2
//     )
// }
//  返回
const goBack = () => {
  router.replace({ path: "/production/coverReport" });
  setTimeout(() => {
    tagsViewStore.delView(route);
  }, 0);
};

// 清除主键
const clearId = (list, key) => {
  if (list.length > 0) {
    list.forEach((item) => {
      delete item[key];
    });
  }
};
// 保存
const submitForm = async () => {
  try {
    await userRef.value.validate();
    form.value.type = 4 //覆膜
    form.value.status = 0; //0:未审核 1：已审核  2：审核未通过
      await addCover({
        ...form.value,
        orderUserList: orderUserList.value,
        orderWorkList: orderWorkList.value,
      });
      ElMessage({
        message: "提交成功",
        type: "success",
      });
      router.push("todo");
  } catch (error) {
    // if (Object.keys(error)?.join(',').includes('.')) {
    //     const errInfoList = Object.values(error)
    //     const err = []
    //     errInfoList.forEach(item => {
    //         err.push(item[0].message)
    //     })
    //     ElMessage({
    //         message: `请将${err.join('、')}信息补充完整`,
    //         type: 'warning',
    //     })
    // }
  }
};
if (route.query.id) {
  getWorkBranch();
}
</script>

<style lang="scss" scoped>
.app {
  padding: 20px;
}

.footer {
  background-color: #eb722f;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 42px;
  line-height: 42px;
  z-index: 9999;
}

.title {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 50px;
  line-height: 50px;
  box-sizing: border-box;
  font-weight: 700;
  font-size: 16px;
  .icon {
    width: 30px;
    height: 56px;
    border: 3px solid #eb722f;
    border-right: 0px;
    border-radius: 5px 0 0 5px;
    background-color: #fcf2e7;
    color: #eb722f;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .title-left {
    flex: 1;
    border: 3px solid #eb722f;
    // border-radius: 5px 0 0 5px;
    border-left: 0px;
    background-color: #fcf2e7;
    color: #eb722f;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .title-right {
    height: 56px;
    width: 100px;
    background-color: #eb722f;
    border-radius: 0 5px 5px 0;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #fff;
  }
}
</style>
